/*
 * Copyright (c) 2012,东方口岸科技有限公司
 * All rights reserved.
 * 文件名称：RouterMessageSender.java
 * 摘    要：
 * 版本：1.0
 * 作    者：fengzhiyong
 */
package com.cneport.transfer.router.biz;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.cneport.transfer.router.model.SendMessage;
import com.cneport.transfer.router.support.service.SendMessageService;
import com.cneport.transfer.util.UtilTools;
import com.cneport.transfer.util.XmlSerializer;

/**
 *@CreateDate:2012-7-11
 *@Description:报文发送器
 */
@Component
public class MessageSender {
    
    private static Logger logger = Logger.getLogger(MessageSender.class);
    
    @Value("${Server.CtlSendFolder}")
    private String filePath;
    
    @Autowired
    private SendMessageService sendMessageService;
    
    public void sendMessageToFile() throws Exception{
        List<SendMessage> sendMessageList=sendMessageService.selectSendMessage();
        if(UtilTools.isNotNullAndZeroList(sendMessageList)){
            
            for(SendMessage sendMessage:sendMessageList){
                try {
                    String stringName=filePath;
                    File bkPath = new File(stringName);
                    
                    if (!bkPath.exists()) {
                        // 创建目录
                        bkPath.mkdirs();
                    }
                    stringName += "VM-Send-" + sendMessage.getMessageId()
                            + ".xml";
                    logger.info(stringName);
                    String xmlMessage=new String(sendMessage.getContent(),"UTF-8");
                    OutputStreamWriter writer = new OutputStreamWriter(
                            new FileOutputStream(stringName), "UTF-8");
                    writer.write(XmlSerializer.formatXML(xmlMessage));
                    writer.flush();
                    writer.close();                  
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    logger.error("XML报文转换错误！编码格式不正确！");
                }
            }
        }else{
            logger.info("待发送表中没有数据，不能进行报文下发！"); 
        }
    }
}
